<template>
  <div>
    <MyTable :arr="list">
      <!-- 绑定slot 对应 mytable -->
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #mytd="{ row: obj2, indd: delIndex }">
        <td>{{ obj2.id }}</td>
        <td>{{ obj2.goods_name }}</td>
        <td>{{ obj2.goods_price }}</td>
        <td>
          <input
            v-if="obj2.inputVisible"
            class="tag-input form-control"
            type="text"
            v-model="obj2.inputValue"
            v-focus
            @blur="blurFn(obj2)"
            @keyup.enter="addFn(obj2)"
            @keyup.esc="escFn(obj2)"
          />
          <button
            v-else
            class="btn btn-primary btn-sm add-tag"
            @click="obj2.inputVisible = true"
          >
            +Tag
          </button>
          <span
            class="badge badge-warning"
            v-for="tag in obj2.tags"
            :key="tag"
            >{{ tag }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="del(delIndex)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable";
import axios from "axios";
axios.defaults.baseURL = "https://www.escook.cn";
export default {
  directives: {},
  data() {
    return {
      list: [],
    };
  },
  async created() {
    // await会等待后面的promise对象(内部ajax请求)成功,并把then里res值取出来放到原地
    const res = await axios({
      url: "/api/goods",
    });
    console.log(res);
    this.list = res.data.data;
  },
  components: {
    MyTable,
  },
  methods: {
    del(index) {
      this.list.splice(index, 1);
    },
    // 失焦
    blurFn(obj) {
      obj.inputVisible = false;
    },
    addFn(obj) {
      if (obj.inputValue.trim().length == 0) {
        alert("请写标签");
        return;
      }
      obj.tags.push(obj.inputValue);
      obj.inputVisible = false;
    },
    escFn(obj) {
      obj.inputValue = "";
    },
  },
  directives: {
    focus: {
      inserted(val) {
        val.focus();
      },
    },
  },
};
</script>

<style scoped>
.badge {
  margin-right: 5px;
}
</style>